package com.imooc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * 自定义Java类加载器实现java热加载
* @ClassName: MyClassLoader 
* @Description: TODO 
* @author zyd
* @date 2017年12月12日 下午3:57:42
 */
public class MyClassLoader extends ClassLoader{
	
	//要加载的java类的classpath路径
	private String classpath;
	
    public MyClassLoader(String classpath){
    	super(ClassLoader.getSystemClassLoader());
    	this.classpath = classpath;
    }
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException{
		//字节数组
		byte[] data = this.loadClassData(name);
		
		return this.defineClass(name, data, 0, data.length);
		//return super.findClass(name);
	}

	/**
	 * 加载Class文件中的内容
	* @Title: loadClassData 
	* @Description: TODO
	* @param @param name
	* @param @return 设定文件 
	* @return 返回类型 
	* @throws
	 */
	private byte[] loadClassData(String name) {
		try{
			name = name.replace(".", "//");
			FileInputStream is = new FileInputStream(new File(classpath+ name + ".class"));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int b = 0;
			while((b = is.read())!= -1){
				baos.write(b);
			}
			is.close();
			return baos.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
